# -*- coding: utf-8 -*-

import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json,time
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "天下无疾重大疾病保险"

    # 生成产品信息
    def genProductInfo(self):

        plan = {
            "planA":{
                "year":[str(i) for i in range(0,76)],
                "gender":["M","F"],
                "money":["100000"],
                "expire":["1年"],
                "payType":["年缴"],
                "plan":["安心计划"]
            },
            "planB": {
                "year": [str(i) for i in range(0, 76)],
                "gender": ["M", "F"],
                "money": ["200000"],
                "expire": ["1年"],
                "payType": ["年缴"],
                "plan": ["升级计划"]
            },
            "planC": {
                "year": [str(i) for i in range(0, 76)],
                "gender": ["M", "F"],
                "money": ["500000"],
                "expire": ["1年"],
                "payType": ["年缴"],
                "plan": ["尊享计划"]
            }
        }

        for k in plan:
            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["expire"],plan[k]["payType"],plan[k]["plan"]):
                #写入数据库
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5]

                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5]

                ) )

    #执行爬虫
    def requestJson(self,dt=None):

        data = {
            "appName":"",
            "appSex": dt["gender"],
            "appidType": "A",
            "appidNo": "110101201803072672",
            "appBirthday": "{year}-02-02".format( year = str(2020-int(dt["year"]))),
            "appPhone":"",
            "appPro": "110000",
            "appCity": "110100",
            "appAddress":"",
            "appEmail":"",
            "name":"",
            "sex": "M",
            "idType": "A",
            "idNo": "110101201803072672",
            "birthday": "{year}-02-02".format( year = str(2020-int(dt["year"]))),
            "phone":"",
            "pro": "110000",
            "city": "110100",
            "address":"",
            "email":"",
            "source": "CUS000000046",
            "planCode": "P000000535",
            "planAmnt": dt["money"],
            "polTerm": "1",
            "poltermType": "Y",
            "payPeriod": "1",
            "payIntv": "12",
            "relation": "0",
            "validate":"",
        }

        payload = urlencode( data ).replace("+","")

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and r.json()["success"]:

            price = Helper.decimalParse( r.json()["msg"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)
            print("/*产品信息更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }

            self.mysql.updateTask(data)

            self.requestJson(dt)
